from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from chaojiying import Chaojiying
import logging
import time

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')

username = 'Cthousand'
password = input('password:')
soft_id = '931779'
captcha_kind = '1006'

client = Chaojiying(username=username, password=password, soft_id=soft_id)
browser = webdriver.Chrome()


def login():
    browser.get('https://captcha8.scrape.center/')
    browser.find_element(
        by=By.CSS_SELECTOR, value='.username input[type="text"]').send_keys('admin')
    browser.find_element(
        by=By.CSS_SELECTOR, value='.password input[type="password"]').send_keys('admin')
    captcha = browser.find_element(
        by=By.CSS_SELECTOR, value='#captcha').screenshot_as_png
    with open('项目2/captcha/captcha.png', 'wb') as f:
        f.write(captcha)
    file_name = '项目2/captcha/captcha.png'
    captcha_result = client.post_pic(
        open(file_name, 'rb').read(), captcha_kind).get('pic_str')
    time.sleep(1)
    logging.info(f'captcha:{captcha_result}')
    browser.find_element(
        by=By.CSS_SELECTOR, value='.captcha input[type="text"]').send_keys(captcha_result)
    browser.find_element(by=By.CSS_SELECTOR, value='.login').click()
    try:
        WebDriverWait(browser, 10).until(EC.presence_of_element_located(
            (By.XPATH, '//h2[contains(., "登录成功")]')))
        # browser.close()
        logging.info('登录成功！')
    except TimeoutException:
        logging.error('超时！')
    browser.close()


if __name__ == '__main__':
    login()
